import { defineStore } from 'pinia'
import { ref } from 'vue'
import { setItem, getItem, removeItem } from '@/utils/localStorage'
import request from '@/api'

export default defineStore('auth', () => {
  const token = ref(getItem('TOKEN'))
  const username = ref('')
  const name = ref('')
  const company = ref({
    name: '',
    logo: '',
    number: '',
    ip_status: null,
  })
  const clip_num = ref(0)

  const isLogin = () => {
    return !!token.value
  }

  const login = (user) => {
    token.value = user.token
    username.value = user.username
    name.value = user.name
    company.value.name = user.company.name
    company.value.logo = user.company.logo
    company.value.number = user.company.number
    company.value.ip_status = user.company.ip_status
    clip_num.value = user.clip_num
    document.title = company.value.name
    setItem('TOKEN', token.value)
  }

  const getUserInfo = async () => {
    const user = await request.get('/auth/user')
    name.value = user.name
    username.value = user.username
    company.value.name = user.company.name
    company.value.logo = user.company.logo
    company.value.number = user.company.number
    company.value.ip_status = user.company.ip_status
    clip_num.value = user.clip_num
    // document.title = company.value.name
  }

  const clear = () => {
    token.value = ''
    username.value = ''
    name.value = ''
    company.value.name = ''
    company.value.logo = ''
    company.value.number = ''
    company.value.ip_status = null
    document.title = ''
    clip_num.value = 0
    removeItem('TOKEN')
  }

  return {
    token,
    username,
    name,
    company,
    clip_num,

    isLogin,
    login,
    getUserInfo,
    clear,
  }
})
